using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Primitives;

namespace Extensions.Configuration.Database
{
    /// <summary>
    /// 默认数据库提供者
    /// default <see cref="IDatabaseProvider"/> .
    /// </summary>
    public class DefaultDatabaseProvider : IDatabaseProvider
    {
        internal DatabaseWatcher Watcher { get; set; }

        public IDictionary<string, string> Load(DbContextOptions<ConfigurationDatabaseContext> dbContextOptions)
        {
            using var databaseContext = new ConfigurationDatabaseContext(dbContextOptions);

            databaseContext.Database.EnsureCreated();

            var task = databaseContext.ConfigurationEntities
                .ToDictionaryAsync(c => c.Key, c => c.Value);

            Task.WaitAll(task);

            return task.Result;
        }

        public IChangeToken Watch(DbContextOptions<ConfigurationDatabaseContext> dbContextOptions)
        {
            this.Watcher ??= this.CreateWatcher();
            return this.Watcher.CreateChangeToken(dbContextOptions);
        }

        internal DatabaseWatcher CreateWatcher()
        {
            return new DatabaseWatcher();
        }
    }
}